package space.lzhq.playground;

import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;

public class XmlToJson {

    public static void main(String[] args) {
        String xml = "<note>\n" +
                         "<to>George</to>\n" +
                         "<from>John</from>\n" +
                         "<heading>Reminder</heading>\n" +
                         "<body>Don't forget the meeting!</body>\n" +
                         "</note>";

        TimeInterval interval = new TimeInterval();
        System.out.println(xml2Json1(xml));
        System.out.println(interval.interval());
        interval.restart();
        System.out.println(xml2Json2(xml));
        System.out.println(interval.interval());
    }

    public static String xml2Json1(String xml) {
        try {
            JsonNode jsonNode = new XmlMapper().readTree(xml);
            return new ObjectMapper().writeValueAsString(jsonNode);
        } catch (IOException e) {
            return String.format("{\"error\": \"%s\"}", e.getMessage());
        }
    }

    public static String xml2Json2(String xml) {
        JSONObject jsonObject = JSONUtil.parseFromXml(xml);
        return jsonObject.toString();
    }


}
